package com.heima.comment.service.impl;

import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.comment.vos.ApCommentVo;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.redis.lock.RedissonDistributedLock;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    UserFeign userFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 查询文章评论列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        //1 参数检查
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }

        // size=10
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            dto.setSize(10);
        }

        //热点评论
        List<ApComment> apCommentList = null;
        if (dto.getIndex() == 1) {  // 首页

            //1 查询热点评论 5
            apCommentList = mongoTemplate.find(Query.query(Criteria
                            .where("entryId").is(dto.getArticleId())
                            .and("type").is(0)
                            .and("flag").is(1))
                            .with(Sort.by(Sort.Direction.DESC,"likes"))
                    ,ApComment.class);
            //2 查询普通评论
            List<ApComment>  apComments =  mongoTemplate.find(Query.query(Criteria
                                    .where("entryId").is(dto.getArticleId())
                                    .and("type").is(0).and("createdTime").lt(dto.getMinDate())
                                    .and("flag").is(0))
                                    .limit(dto.getSize() - apCommentList.size())
                                    .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                            ,ApComment.class);

            //3 合并结果
            apCommentList.addAll(apComments);

        } else { // 不是首页,查询普通评论
            //2 查询评论列表
             apCommentList =mongoTemplate.find(Query.query(Criteria
                            .where("entryId").is(dto.getArticleId())
                            .and("type").is(0).and("createdTime").lt(dto.getMinDate())
                            .and("flag").is(0))
                            .limit(dto.getSize())
                            .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                    , ApComment.class);
        }


        //3 处理 评论点赞回显
        // 如果当前用户未登录，直接返回
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(apCommentList);
        }

        // 如果用户登录，处理回显
        // 获取当前文章的所有的评论id
        List<String> idList = apCommentList.stream().map(comment -> comment.getId())
                .collect(Collectors.toList());
        // 返回回显的评论带点赞
        List<ApCommentVo> apCommentVos = new ArrayList<>();
        if (idList != null && idList.size() > 0) {  // 评论列表 select * from ta where commentId in()

            Query query = Query.query(Criteria.where("commentId").in(idList)
                    .and("authorId").is(user.getId()).and("operation").is(0));

            List<ApCommentLike> commentLikeList = mongoTemplate.find(query, ApCommentLike.class);

            if (commentLikeList != null && commentLikeList.size() > 0) {  // 有点赞
                // 评论列表
                apCommentList.forEach( apComment -> {

                    ApCommentVo apCommentVo = new ApCommentVo();
                    BeanUtils.copyProperties(apComment, apCommentVo);

                    // 评论点赞列表
                    commentLikeList.forEach(commentLike->{
                        // 判断点赞
                        if (apComment.getId().equals(commentLike.getCommentId()) && commentLike.getOperation() == 0) {
                            apCommentVo.setOperation((short) 0);
                        }
                    });
                    apCommentVos.add(apCommentVo);
                } );

                return ResponseResult.okResult(apCommentVos);
            }else {
                return ResponseResult.okResult(apCommentList);
            }
        }


        //4 返回数据
        return ResponseResult.okResult(apCommentList);
    }

    /**
     * 保存评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //1 参数检查
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 文章评论内容
        if (StringUtils.isBlank(dto.getContent()) || dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 获取当前登录人
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 查询APUser用户信息
        Integer loginUserId = user.getId();
        user = userFeign.findUserById(loginUserId.longValue());
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "非法账号");
        }

        // 内容安全检查 （自行实现）


        //2 保存评论
        ApComment apComment = new ApComment();
        apComment.setContent(dto.getContent());
        apComment.setAuthorId(loginUserId);
        apComment.setAuthorName(user.getName());
        apComment.setImage(user.getImage());
        apComment.setEntryId(dto.getArticleId());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        mongoTemplate.save(apComment);


        //3 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    CommentHotService commentHotService;

    @Autowired(required = false)
    RedissonDistributedLock lock;

    /**
     * 评论的点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //1 参数检查
        if (dto == null || dto.getCommentId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 获取当前登录人
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 查询APUser用户信息
        Integer loginUserId = user.getId();
        user = userFeign.findUserById(loginUserId.longValue());
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "非法账号");
        }

        // 查询评论
        ApComment comment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (comment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "暂无评论");
        }

        // 用户是否重重复点赞
        Query query = Query.query(Criteria
                .where("commentId").is(dto.getCommentId())
                .and("authorId").is(user.getId())
        );
        ApCommentLike commentLike = mongoTemplate.findOne(query, ApCommentLike.class);
        if (commentLike != null && dto.getOperation()==0  && commentLike.getOperation()==0 ) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已点赞");
        }

        //3 保存点赞  // TODO bug
        RLock rlock = this.lock.lock("leadnews:comment");
        try {

            if ( dto.getOperation().intValue() == 0) {

                // 保存点赞评论信息
                if (commentLike == null) {// 第一次点赞
                    commentLike = new ApCommentLike();
                    commentLike.setAuthorId(user.getId());
                    commentLike.setCommentId(comment.getId());
                }

                commentLike.setOperation(dto.getOperation());
                mongoTemplate.save(commentLike);

                // 更新点赞数
                comment.setLikes(comment.getLikes() + 1);
                mongoTemplate.save(comment);


                // 计算热点评论  异步调用
                if (comment.getLikes() >= 5) {
                    commentHotService.hotCommentExecutor(comment.getEntryId(), comment);
                }

            } else { // 取消点赞

                commentLike.setOperation((short) 1);  // 取消点赞
                mongoTemplate.save(commentLike);


                comment.setLikes(comment.getLikes() <= 1 ? 0 : comment.getLikes() - 1);
                mongoTemplate.save(comment);
            }
        } finally {
            lock.unlock(rlock);
        }


        //4 返回结果
        Map<String, Integer> resultMap = new HashMap<>();
        resultMap.put("likes", comment.getLikes());

        return ResponseResult.okResult(resultMap);
    }

}
